package com.opNaga.bpmp.requirement;

import com.opNaga.bpmp.BPMPElement;

import java.util.*;

/**
 * User: Junyi BEI
 * Date: 01/02/2012
 * Time: 16:07
 */
public abstract class Requirement extends BPMPElement {
  private Set<BPMPElement> preceded = new HashSet<BPMPElement>();

  public Requirement() {
    super();
  }
  
  public Requirement(String n) {
    super(n);
  }

  public boolean addPrecededRequirement(BPMPElement bc) {
    if(!getClass().isAssignableFrom(bc.getClass())) {
      return standardMessage(780, bc);
    }
    Collection<BPMPElement> cs = ((Requirement) bc).getCandidates();
    if(cs.contains(this)) {
      return standardMessage(781, bc);
    }
    if(!preceded.add(bc)) {
      return standardMessage(782, bc);
    }
    return standardMessage(788, bc);
  }

  public boolean removeSucceeder(BPMPElement bc) {
    if(!getClass().isAssignableFrom(bc.getClass())) {
      return standardMessage(783, bc);
    }
    if(!preceded.remove(bc)) {
      return standardMessage(784, bc);
    }
    return standardMessage(789, bc);
  }

  public Iterator<BPMPElement> iterateSucceeders() {
    return new ArrayList<BPMPElement>(preceded).iterator();
  }

  public Collection<BPMPElement> getCandidates() {
    Set<BPMPElement> succs = new HashSet<BPMPElement>();
    for(BPMPElement bc : preceded) {
      succs.addAll(((Requirement) bc).getCandidates());
    }
    succs.add(this);
    return succs;
  }
}
